﻿using BlogFile.Application.DTO;
using BlogFile.Domain;
using BlogFile.Repository;
using Core.CPlatform;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BlogFile.Application.Service.Imp
{
    public class UploadFileService : IUploadFileService
    {
        private IUploadFileRepository _uploadFileRepository;
        public UploadFileService(IUploadFileRepository uploadFileRepository)
        {
            _uploadFileRepository = uploadFileRepository;
        }
        public async Task<UploadResultDTO> UploadFile(HttpRequest request)
        {
            var file = request.Form.Files[0];
            string fileName = file.FileName;
            int index = fileName.LastIndexOf('.');
            string extension = fileName.Substring(index, fileName.Length - index);//获取后缀名
            string guid = Guid.NewGuid().ToString().Replace("-", "");//生成guid
            string newFileName = guid + extension;
            DateTime now = DateTime.Now;
            //路径日期部分 windows为\，linux为/
            //string datePath = string.Format(@"{0}\{1}\{2}", now.Year, now.Month, now.Day);
            string datePath = string.Format("{0}/{1}/{2}", now.Year, now.Month, now.Day);
            var rootSection = ConfigureProvider.configuration.GetSection("Upload");
            //string path = string.Format(@"{0}\{1}", rootSection.GetSection("SavePath").Value, datePath);
            string path = string.Format("{0}/{1}", rootSection.GetSection("SavePath").Value, datePath);
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);
            UploadResultDTO uploadResultDTO = new UploadResultDTO();
            using (FileStream fileStream = File.Create(path +"/"+ newFileName))
            {
                await file.CopyToAsync(fileStream);
                await fileStream.FlushAsync();
                //浏览器显示虚拟路径
                string virtualPath = string.Format("{0}/{1}/{2}/{3}", rootSection.GetSection("Url").Value, 
                    rootSection.GetSection("VirtualPath").Value,datePath,newFileName);
                uploadResultDTO.FileName = newFileName;
                uploadResultDTO.Uploaded = 1;
                uploadResultDTO.Url = virtualPath;
            }
            UploadFile uploadFile = new UploadFile();
            uploadFile.CreateTime = now;
            uploadFile.Extension = extension;
            uploadFile.FileName = fileName;
            uploadFile.Size = file.Length;
            uploadFile.Guid = guid;
            uploadFile.SavePath = uploadResultDTO.Url;
            await _uploadFileRepository.InsertAsync(uploadFile);            
            return uploadResultDTO;
        }
    }
}
